package org.study.id.other.util;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * 分布式ID生成算法：基于Zookeeper
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年04月23日
 */
public class Zookeeper01IdWorker {
    private ZooKeeper zk;
    private final String path = "/id-generator";

    public static Zookeeper01IdWorker of(String connectString) {
        return new Zookeeper01IdWorker(connectString);
    }

    private Zookeeper01IdWorker(String connectString) {
        try {
            zk = new ZooKeeper(connectString, 3000, event -> {
                System.out.println(event.toString());
            });
            if (zk.exists(path, false) == null) {
                zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (IOException | KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public int nextId() {
        try {
            Stat stat = zk.setData(path, new byte[0], -1);
            return stat.getVersion();
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
